<template>
	<page-meta :root-font-size="getRootFontSize()"></page-meta>
	<view class="mask" @touchmove.stop.prevent="moveStop" v-if="MaskBox">
		<view class="clickMask" @tap="removeMaskBox(MaskBox, $event)">
			<image style="width:100%; height: 100%; transform: scale(1.5);" mode="scaleToFill" src="/static/icon/AboutUs/2x/homeImg.png"></image>
		</view>
		<view class="loginBox">
			<view class="titleBox">{{ i18n.ctwfont1 }}</view>
			<!-- <view class="welcomeTitle">{{ isShow ? i18n.ctwfont9 : i18n.ctwfont7 }}</view> -->
			<!-- 账号登录 -->
			<uni-forms v-model="login" ref="form" :rules="rules" :border="false" validateTrigger="bind" v-if="isShow">
				<uni-forms-item label=" " :labelWidth="30" name="username" class="formItemBox">
					<template #left>
						<uni-icons size="24" type="person-filled" style="padding-left: 5px;" color="#F77687" />
						<!-- <image style="width: 25px; height: 25px;" src="/static/icon/superAnt/unity3d@2x.png" mode=""></image> -->
					</template>
					<input
						type="text"
						class="classInput"
						:maxlength="20"
						v-model="login.username"
						:placeholder="i18n.ctwfont4"
						placeholder-style="color: #7F7F7F"
						@input="binddata('username', $event.detail.value)"
					/>
					<uni-icons v-show="login.username" @tap="nameDele" class="nameIcon" color="#9e9fa0" type="closeempty" size="20" />
				</uni-forms-item>
				<uni-forms-item label=" " :labelWidth="30" name="password" class="formItemBox">
					<template #left>
						<uni-icons size="24" type="locked-filled" style="padding-left: 5px;" color="#F77687" />
						<!-- <image style="width: 25px; height: 25px;" src="/static/icon/superAnt/unity3d@2x(3).png" mode=""></image> -->
					</template>
					<input
						type="text"
						class="classInput"
						:maxlength="28"
						:password="eyeShow"
						v-model="login.password"
						:placeholder="i18n.ctwfont5"
						@input="binddata('password', $event.detail.value)"
					/>
					<uni-icons v-show="login.password" @tap="passDele" class="nameIcon" color="#9e9fa0" type="closeempty" size="20" />
					<uni-icons v-show="login.password" @tap="eyeopen" class="nameIcon2" color="#9e9fa0" :type="eye" size="20" />
				</uni-forms-item>
				<view class="submitBtn">
					<button @tap="Submit" :loading="loading" :disabled="loading" size="mini" class="loginBtn" type="default">{{ i18n.ctwfont1 }}</button>
				</view>
				<view class="radioBox"><!-- <view @tap="shouji()">{{ isShow ? i18n.ctwfont7 : i18n.ctwfont9 }}</view> --></view>
				<view class="bottomBoxGo">
					<!-- <view class="xiahuaxiang" @tap="goRegister">{{ i18n.ctwfont2 }}</view> -->
					<view class=""></view>
					<view class="xiahuaxiang" @tap="zhaohuiMM">{{ i18n.ctwfont8 }}？</view>
				</view>
			</uni-forms>
			<!-- 手机号 -->
			<!-- v-show="!isShow" -->
			<uni-forms v-model="login2" ref="form2" :rules="rules2" validateTrigger="bind" v-if="langShow" v-show="!isShow">
				<uni-forms-item label=" " :labelWidth="45" name="phone2" class="formItemBox">
					<picker class="pickerBox" @change="bindPickerChange" :value="index" :range="array">
						<view class="pickerBoxImg"><image style="width: 100%; height: 100%;" mode="scaleToFill" :src="arrayimg[index]"></image></view>
					</picker>
					<input
						type="number"
						class="classInput"
						:maxlength="11"
						v-model="login2.phone2"
						:placeholder="i18n.ctwfont10"
						@input="binddata('phone2', $event.detail.value)"
					/>
					<!-- <input type="number" :maxlength="11" class="classInput" v-model="login2.phone2" placeholder="请输入手机号" @input="binddata('phone2', $event.detail.value)" /> -->
					<uni-icons v-show="login2.phone2" @tap="phoneDele" class="nameIcon" color="#9e9fa0" type="closeempty" size="20" />
				</uni-forms-item>
				<uni-forms-item label=" " :labelWidth="1" name="phone" class="formItemBox">
					<input type="number" :maxlength="4" class="classInput" v-model="login2.yzm" :placeholder="i18n.ctwfont11" />
					<uni-icons v-show="login2.yzm" @tap="yzmDele" class="nameIcon" color="#9e9fa0" type="closeempty" size="20" />
					<text v-show="!login2.yzm" size="mini" @tap="getPhoneNum" class="zhPassword" :style="{ color: canClick ? '#cccccc' : '#CD001B' }">{{ contents }}</text>
				</uni-forms-item>
				<view class="submitBtn">
					<button @tap="loginTwoSubmit" :loading="loadingTwo" :disabled="loadingTwo" size="mini" class="loginBtn" type="default">{{ i18n.ctwfont1 }}</button>
				</view>
				<view class="radioBox"><!-- <view @tap="shouji()">{{ isShow ? i18n.ctwfont7 : i18n.ctwfont9 }}</view> --></view>
				<view class="bottomBoxGo">
					<!-- <view class="xiahuaxiang" @tap="goRegister">{{ i18n.ctwfont2 }}</view> -->
					<view class=""></view>
					<view class="xiahuaxiang" @tap="zhaohuiMM">{{ i18n.ctwfont8 }}？</view>
				</view>
			</uni-forms>
		</view>
	</view>
</template>

<script>
import { setStorage, setCookie, removeCookie, removeAllCookie, getCookie, getStorage, removeStorage } from '@/utils/setStorage.js';
import LanguageConfig from '@/i18n/LanguageConfig';
import { baseUrl } from '@/utils/http.js';
import { codeMapFun } from '@/utils/codeMap.js';
import { loadFontFace } from '@/utils/loadFontFaceBox.js';
import baseFont from '@/utils/baseFont.js';
import { setTabBar } from '@/utils/setTabBar.js';
export default {
	extends: baseFont,
	name: 'loginPages',
	props: {
		MaskBox: {
			type: Boolean,
			default: false
		}
	},
	watch: {
		index: {
			deep: true,
			handler(newVal, oldVal) {
				this.contents = this.$t('login').ctwfont86;
			}
		},
		'login.username': {
			deep: true,
			handler(newVal, oldVal) {
				if (newVal) {
					this.login.username = newVal.toUpperCase();
				}
			}
		}
	},
	computed: {
		i18n() {
			return this.$t('login');
		},
		array() {
			return [`${this.$t('login').ctwfont87}-86`, `${this.$t('login').ctwfont90}-66`, `${this.$t('login').ctwfont88}-84`];
		},
		rules() {
			return {
				// 验证用户名
				username: {
					rules: [
						{ required: true, errorMessage: this.$t('login').ctwfont131, trigger: 'blur' },
						{ minLength: 2, maxLength: 20, errorMessage: 'The length is 6 - 28 characters', trigger: 'blur' }
					]
				},
				// 验证密码
				password: {
					rules: [
						{ required: true, errorMessage: this.$t('login').ctwfont132, trigger: 'blur' },
						{ minLength: 6, maxLength: 28, errorMessage: this.$t('login').ctwfont125, trigger: 'blur' }
						// { pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,28}$/, errorMessage: '请输入正确的密码', trigger: 'blur' }
					]
				}
			};
		},
		rules2() {
			return {
				phone2: {
					rules: [
						{ required: true, errorMessage: this.$t('login').ctwfont104, trigger: 'blur' },
						{
							validateFunction: this.mobileValidateFunction
						}
						// { pattern: /^1(3|4|5|6|7|8|9)\d{9}$/, errorMessage: '请输入正确的手机号', trigger: 'blur' }
					]
				}
			};
		}
	},
	created() {
		const languageFlag = getStorage('language') || 'th';
		if (languageFlag === 'zh') {
			this.index = 0;
		} else if (languageFlag === 'th') {
			this.index = 1;
		} else {
			this.index = 2;
		}
	},
	data: function() {
		return {
			login: {
				username: '',
				password: ''
			},
			login2: {
				phone2: '',
				yzm: ''
			},
			// 显示隐藏眼睛图标
			eye: 'eye-slash',
			eyeShow: true,
			langShow: true, // 切换语言时校验更新
			isShow: true,
			secondNum: 300,
			contents: this.$t('login').ctwfont86,
			canClick: false,
			clock: '',
			// 国籍ID
			index: 0,
			// 国籍arr
			arrayimg: ['/static/icon/china.png', '/static/icon/thailand.png', '/static/icon/vietnam.png'],
			loading: false, // 加载
			loadingTime: '', // 定时
			loadingTwo: false, // 加载手机号
			loadingTwoTime: '', // 定时
		};
	},
	methods: {
		// 取消登录
		removeMaskBox(val, e) {
			// console.log(e)
			e.stopPropagation();
			e.preventDefault();
			this.$emit('removeLoginMaskBox', val);
		},
		// 禁止滑动
		moveStop() {},
		// 账户
		async Submit() {
			const deviceId = getApp().globalData.pushClientId || '';
			const { username, password } = this.login;
			const params2 = {
				username: username,
				password: password,
				deviceType: plus.os.name == 'iOS' ? 1 : 0,
				deviceId: deviceId
			};
			this.$refs.form
				.validate()
				.then(async val => {
					this.loading = true;
					this.loadingTime = setTimeout(() => {
						this.loading = false;
					}, 5000);
					if (getCookie(baseUrl)) {
						removeCookie(baseUrl);
						removeAllCookie();
					}
					if (getStorage('token')) {
						removeStorage('token');
					}
					// 第一个参数url, 第二个参数请求数据, 第三个请求方式
					const { data: res } = await this.$http(true, 'api/user/login', params2, 'POST');
					if (res.errno === 0) {
						setCookie(baseUrl, res.data.token);
						setStorage('token', res.data.token);
						const obj = {
							type: 'login',
							value: 1
						};
						setStorage('tokenNum', obj); // 登录成功时重置
						setStorage('userconter', JSON.stringify(res.data.user));
						if (res.data.user) {
							const panDuan = await this.jurisdiction(res.data.user.customerCode);
							if (panDuan) {
								this.$emit('loginSubmit', true);
							} else {
								this.$emit('loginSubmit', true);
							}
						} else {
							this.$emit('loginSubmit', true);
						}
						this.loading = false;
						clearTimeout(this.loadingTime);
						uni.showToast({
							title: 'Login successful',
							icon: 'none',
							position: 'top'
						});
					} else {
						this.loading = false;
						clearTimeout(this.loadingTime);
						const err = codeMapFun().find(item => item[res.errno]);
						if (err) {
							uni.showToast({
								title: err[res.errno],
								icon: 'none',
								position: 'top'
							});
						} else {
							uni.showToast({
								title: res.errmsg,
								icon: 'none',
								position: 'top'
							});
						}
					}
				})
				.catch(err => {
					uni.showToast({
						title: 'Please fill in the correct information',
						icon: 'none',
						position: 'top'
					});
				});
		},
		// 手机校验
		mobileValidateFunction(rule, value, data, callback) {
			if (this.index === 0) {
				var re = new RegExp(/^1(3|4|5|6|7|8|9)\d{9}$/);
				if (re.test(value)) {
					return true;
				} else {
					callback(this.$t('login').ctwfont114);
				}
			} else if (this.index === 1) {
				return true;
			} else {
				return true;
			}
			// if (value !== this.formList3.password) {
			// 	callback('密码不一致');
			// }
		},
		// 手机号
		loginTwoSubmit() {
			const deviceId = getApp().globalData.pushClientId || '';
			const { phone2, yzm } = this.login2;
			const params = {
				mobile: phone2,
				code: yzm,
				deviceType: plus.os.name == 'iOS' ? 1 : 0,
				deviceId: deviceId
			};
			this.$refs.form2
				.validate()
				.then(async val => {
					this.loadingTwo = true;
					this.loadingTwoTime = setTimeout(() => {
						this.loadingTwo = false;
					}, 5000);
					if (getCookie(baseUrl)) {
						removeCookie(baseUrl);
						removeAllCookie();
					}
					if (getStorage('token')) {
						removeStorage('token');
					}
					// 第一个参数url, 第二个参数请求数据, 第三个请求方式
					const { data: res } = await this.$http(true, 'api/user/mobileLogin', params, 'POST');
					if (res.errno === 0) {
						setCookie(baseUrl, res.data.token);
						setStorage('token', res.data.token);
						const obj = {
							type: 'login',
							value: 1
						};
						setStorage('tokenNum', obj); // 登录成功时重置
						setStorage('userconter', JSON.stringify(res.data.user));
						this.$emit('loginSubmit', true);
						if (res.data.user) {
							const panDuan = await this.jurisdiction(res.data.user.customerCode);
							if (panDuan) {
								this.$emit('loginSubmit', true);
							} else {
								this.$emit('loginSubmit', true);
							}
						} else {
							this.$emit('loginSubmit', true);
						}
						this.loadingTwo = false;
						clearTimeout(this.loadingTwoTime);
						uni.showToast({
							title: 'Login successful',
							icon: 'none',
							position: 'top'
						});
					} else {
						this.loadingTwo = false;
						clearTimeout(this.loadingTwoTime);
						const err = codeMapFun().find(item => item[res.errno]);
						if (err) {
							uni.showToast({
								title: err[res.errno],
								icon: 'none',
								position: 'top'
							});
						} else {
							uni.showToast({
								title: res.errmsg,
								icon: 'none',
								position: 'top'
							});
						}
					}
				})
				.catch(err => {
					uni.showToast({
						title: 'Please fill in the correct information',
						icon: 'none',
						position: 'top'
					});
				});
		},
		// 账号
		nameDele() {
			this.login.username = '';
		},
		// 密码
		passDele() {
			this.login.password = '';
			setTimeout(() => {
				this.eye = 'eye-slash';
				this.eyeShow = true;
			}, 500);
		},
		// 手机号
		phoneDele() {
			this.login2.phone2 = '';
		},
		// 验证码
		yzmDele() {
			this.login2.yzm = '';
		},
		// 模式切换
		shouji(val) {
			if (this.isShow === false) {
				this.login = {
					username: '',
					password: ''
				};
				this.isShow = true;
				// return this.$refs.form.resetFields();
			} else {
				this.login2 = {
					phone2: '',
					yzm: ''
				};
				this.isShow = false;
				return this.$refs.form2.resetFields();
			}
		},
		// 获取验证码
		async getPhoneNum() {
			const { phone2 } = this.login2;
			if (phone2) {
				if (this.canClick) {
					return false;
				}
				this.canClick = true;
				let code = '';
				if (this.index === 0) {
					code = '86';
				} else if (this.index === 1) {
					code = '66';
				} else {
					code = '84';
				}
				const params = {
					mobile: phone2,
					areaCode: code
				};
				// 第一个参数url, 第二个参数请求数据, 第三个请求方式
				const { data: res } = await this.$http(true, 'api/user/loginSendMessage', params, 'GET');
				if (res.errno === 0) {
					this.contents = this.secondNum + ' s';
					this.clock = setInterval(() => {
						this.secondNum--;
						this.contents = this.secondNum + ' s';
						if (this.secondNum < 1) {
							// 当倒计时小于0时清除定时器
							clearInterval(this.clock);
							this.contents = this.$t('login').ctwfont86;
							this.secondNum = 300;
							this.canClick = false;
							this.clearCodeNum(params);
						}
					}, 1000);
				} else {
					this.canClick = false;
					const err = codeMapFun().find(item => item[res.errno]);
					if (err) {
						uni.showToast({
							title: err[res.errno],
							icon: 'none',
							position: 'top'
						});
					} else {
						uni.showToast({
							title: res.errmsg,
							icon: 'none',
							position: 'top'
						});
					}
				}
			} else {
				this.$refs.form2.setValue('phone2', phone2);
			}
		},
		// 60秒后清楚验证吗
		async clearCodeNum(item) {
			const params = {
				mobile: item.mobile,
				function: 'LOGIN'
			};
			// 第一个参数url, 第二个参数请求数据, 第三个请求方式
			await this.$http(true, 'api/user/verificationCode/clear', params, 'GET');
		},
		// 找回密码
		zhaohuiMM() {
			// this.$emit('removeLoginMaskBox', true);
			// #ifdef APP-PLUS
			uni.redirectTo({
				url: `/pages/logins/modifyMM`
			});
			// #endif
			// #ifdef H5
			this.$Router.push(`/pages/logins/modifyMM`);
			// #endif
		},
		// 眼睛图标切换
		eyeopen() {
			this.eyeShow = !this.eyeShow;
			if (this.eyeShow) {
				this.eye = 'eye-slash';
			} else {
				this.eye = 'eye';
			}
		},
		// 选择国籍
		bindPickerChange(val) {
			this.langShow = false;
			let lang = 'th';
			this.index = val.target.value;
			if (this.index === 0) {
				lang = 'zh';
			} else if (this.index === 1) {
				lang = 'th';
			} else {
				lang = 'en';
			}
			LanguageConfig.isExist(lang);
			this.$i18n.locale = lang;
			setStorage('language', lang);
			this.$refs.form2.resetFields();
			this.$nextTick(function() {
				loadFontFace();
				this.langShow = true;
				setTabBar();
			});
		},
		// 注册账号
		goRegister() {
			// this.$emit('removeLoginMaskBox', true);
			// #ifdef APP-PLUS
			uni.redirectTo({
				url: `/pages/logins/phone`
			});
			// #endif
			// #ifdef H5
			this.$Router.push(`/pages/logins/phone`);
			// #endif
		},
		// 获取权限
		async jurisdiction(customerCode) {
			const params = {
				customerCode: customerCode
			};
			const { data: res } = await this.$http(true, 'api/customer/permission', params, 'GET');
			if (res.errno === 0) {
				setStorage('jurisdiction', JSON.stringify(res.data) || null);
				return true;
			} else {
				return false;
			}
		}
	}
};
</script>

<style lang="scss" scoped>
::v-deep button[disabled] {
	background-color: #81c5ff;
	color: #ffffff;
}
::v-deep .uni-error-message {
	width: 100%;
}
.mask {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	// background-color: rgba(0, 0, 0, 0.7);
	background-color: rgba(0, 0, 0, 0.9);
	backdrop-filter: blur(5rpx);
	z-index: 99999;
	// pointer-events: none;
	.clickMask {
		position: relative;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-image: url('/static/icon/AboutUs/2x/homeImg.png');
	}
	.loginBox {
		position: absolute;
		top: 40%;
		left: 50%;
		transform: translate(-50%, -50%);
		width: 100%;
		z-index: 9999999;
		// pointer-events: none;
		.titleBox {
			color: #fff;
			padding: 10px 0;
			text-align: center;
			// font-size: $uni-font-size-custom-j;
			font-size: 32px;
			margin-bottom: 30px;
		}
		.welcomeTitle {
			text-align: center;
			font-size: $uni-font-size-custom-g;
			color: #4b4c51;
		}
		.formItemBox {
			border: 2px solid #a8a8a8;
			border-radius: 20px;
		}
		.pickerBox {
			position: absolute;
			left: 5px;
			.pickerBoxImg {
				width: 40px;
				height: 36px;
			}
		}
		.classInput {
			position: relative;
			height: 40px;
			color: #9e9fa0;
			font-size: $uni-font-size-custom-g;
		}
		.nameIcon {
			position: absolute;
			right: 5px;
			top: 8px;
		}
		.nameIcon2 {
			position: absolute;
			right: 28px;
			top: 8px;
		}
		.zhPassword {
			position: absolute;
			right: 10px;
			top: 8px;
			color: #333333;
		}
		.submitBtn {
			display: flex;
			justify-content: center;
			align-items: center;
			.loginBtn {
				background-color: #cd001b;
				padding: 0 35px;
				border-radius: 20px;
				color: #ffffff;
				font-size: $uni-font-size-custom-j;
			}
		}
		.radioBox {
			margin-top: 15px;
			font-size: $uni-font-size-custom-d;
			color: #afcfff;
			display: flex;
			justify-content: center;
		}
		.bottomBoxGo {
			margin-top: 15px;
			display: flex;
			justify-content: space-between;
			align-items: center;
			color: #cd001b;
			.xiahuaxiang {
				font-size: $uni-font-size-custom-g;
				border-bottom: 1px solid #cd001b;
			}
		}
	}
}
</style>
